<?php 
namespace szxh;

class Image {

    private $width;
    private $height;
    private $obj = [];

    public function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    public function push($src, $posx = 0, $posy = 0, $top = 0, $left = 0, $width = true, $height = true, $type = false) {
        $resource = $this->getResource($src);
        $param = [
            'resource' => $resource['resource'],
            'type'     => $resource['type'],
            'ix'       => imagesx($resource['resource']),
            'iy'       => imagesy($resource['resource']),
            'posx'     => $posx,
            'posy'     => $posy,
            'top'      => $top,
            'left'     => $left,
            'width'    => $width,
            'height'   => $height
        ];
        if($posy + $height > $this->height) {
            $this->height = $posy + $height;
        }
        if($posx + $width > $this->width) {
            $this->width = $posx + $width;
        }
        array_push($this->obj, $param);
        return $param;
    }

    private function getResource($src, $type = false) {
        if(empty($type)) {
            if(strpos($src, '.') !== false) {
                $ss = explode('.', $src);
                $suffix = $ss[count($ss) - 1];
            } else {
                $suffix = 'jpg';
            }
        } else {
            $suffix = $type;
        }
        
        switch($suffix) {
            case 'jpg':
            case 'jpeg':
                $img = imagecreatefromjpeg($src);
                $type = 'jpeg';
            break;
            case 'png':
                $img = imagecreatefrompng($src);
                $type = $png;
            break;
            default:
                throw new Exception("暂不支持{$src}图片后缀类型", 1);
                
        }
        return [
            'resource' => $img,
            'type' => $type
        ];
    }

    public function output() {
        $dom = new DOMDocument('1.0', 'UTF-8');
        $image = imagecreatetruecolor($this->width, $this->height);
        foreach ($this->obj as $obj) {
            imagecopyresized($image, $obj['resource'], $obj['posx'], $obj['posy'], $obj['top'], $obj['left'], $obj['width'], $obj['height'], $obj['ix'], $obj['iy']);
        }
        header('Content-type: image/png');
        imagepng($image);
        imagedestroy($image);
    }


}
